package com.pek.control.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.pek.config.Validate;
import com.pek.control.entity.UserEntity;
import com.pek.control.enums.UserLevel;
import com.pek.control.service.IUserService;
import com.pek.control.util.RedisUtil;
import com.pek.util.Constants;
import com.pek.util.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private Validate validate;

    @PostMapping("/register")
    private RestResult<UserEntity> register(@RequestBody UserEntity regUser) {
        if (StringUtils.isBlank(regUser.getUsername()) || StringUtils.isBlank(regUser.getPassword())) {
            return RestResult.error("null");

        }
        if (userService.getUser(regUser.getUsername()) != null) {
            return RestResult.error("用户名已被注册");
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(regUser.getUsername());
        userEntity.setPassword(passwordEncoder.encode(regUser.getPassword()));
        userEntity.setLevel(UserLevel.NORMAL.level);
        userService.save(userEntity);
        return RestResult.success(userEntity);
    }

    @PostMapping("/login")
    private RestResult<String> login(@RequestBody UserEntity loginUser) {
        var user = userService.getUser(loginUser.getUsername(), loginUser.getPassword());
        if (user == null) {
            return RestResult.error("账户名或密码错误");
        }
        String token=Constants.spawnToken(user, redisUtil);
        JSONObject redisObj = new JSONObject();
        redisObj.put("ip", validate.getIp());
        redisObj.put("user", user.getUsername());
        redisObj.put("pwd", user.getPassword());
        redisUtil.set(token, redisObj, 60 * 60 * 24);
        return RestResult.success(token);
    }
}
